import React, { useState, useRef, useEffect } from 'react'
import { Button, Input, Select, Card, message, Avatar, Space, Modal } from 'antd'
import { MessageOutlined, RobotOutlined, UserOutlined, ClearOutlined } from '@ant-design/icons'
import { useAIStore } from '../../store/ai'

const { Search } = Input
const { Option } = Select

interface AIChatWindowProps {
  isOpen: boolean
  onClose: () => void
  member?: any // 可选：关联的家族成员
}

export const AIChatWindow: React.FC<AIChatWindowProps> = ({ 
  isOpen, 
  onClose, 
  member 
}) => {
  const [inputValue, setInputValue] = useState('')
  const [selectedScenario, setSelectedScenario] = useState('general')
  const [selectedRole, setSelectedRole] = useState('assistant')
  const messagesEndRef = useRef<HTMLDivElement>(null)
  
  const { 
    messages, 
    loading, 
    scenarios, 
    roles, 
    currentSessionId,
    sendMessage, 
    loadHistory, 
    clearHistory,
    generateContent 
  } = useAIStore()

  const initialPrompts = [
    '帮我制定春节家族聚会的策划方案',
    '如何设计合理的家族家规？',
    '如何调解家族成员间的矛盾？',
    '有什么好的家族传统传承建议？',
    '帮我写一封缅怀祖先的家书'
  ]

  useEffect(() => {
    if (isOpen) {
      loadInitialData()
    }
  }, [isOpen])

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  const loadInitialData = async () => {
    try {
      await Promise.all([
        loadHistory(currentSessionId),
        loadScenarios(),
        loadRoles()
      ])
    } catch (error) {
      message.error('加载AI助手数据失败')
    }
  }

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  const handleSend = async (text?: string) => {
    const message = text || inputValue.trim()
    if (!message) return

    setInputValue('')
    
    try {
      await sendMessage(message, selectedScenario, selectedRole)
    } catch (error) {
      message.error('发送消息失败')
    }
  }

  const handleClearHistory = async () => {
    try {
      await clearHistory(currentSessionId)
      message.success('聊天记录已清除')
    } catch (error) {
      message.error('清除聊天记录失败')
    }
  }

  const renderMessage = (message: any) => {
    const isUser = message.role === 'user'
    
    return (
      <div key={message.id} className={`flex ${isUser ? 'justify-end' : 'justify-start'} mb-4`}>
        <Space align="start" style={{ maxWidth: '80%' }}>
          {!isUser && (
            <Avatar
              className="flex-shrink-0"
              icon={<RobotOutlined />}
              style={{ backgroundColor: '#1890ff' }}
            />
          )}
          <Card
            size="small"
            style={{ maxWidth: '100%' }}
            className={isUser ? 'bg-blue-50' : ''}
          >
            <div style={{ whiteSpace: 'pre-wrap', fontSize: 14 }}>
              {message.content}
            </div>
            <div style={{ fontSize: 12, color: 'gray', marginTop: 8 }}>
              {message.timestamp}
            </div>
          </Card>
          {isUser && (
            <Avatar
              className="flex-shrink-0"
              icon={<UserOutlined />}
              style={{ backgroundColor: '#52c41a' }}
            />
          )}
        </Space>
      </div>
    )
  }

  return (
    <Modal
      title={
        <Space>
          <RobotOutlined />
          <span>AI家族助手</span>
          {member && <span style={{ color: '#1890ff' }}>- {member.name}</span>}
        </Space>
      }
      open={isOpen}
      onCancel={onClose}
      footer={null}
      width={800}
      centered
    >
      <div style={{ display: 'flex', flexDirection: 'column', height: '600px' }}>
        {/* 设置面板 */}
        <div style={{ marginBottom: 16 }}>
          <Space style={{ width: '100%' }}>
            <Select
              style={{ flex: 1 }}
              placeholder="选择场景"
              value={selectedScenario}
              onChange={setSelectedScenario}
            >
              {scenarios.map((scenario) => (
                <Option key={scenario.id} value={scenario.id}>
                  {scenario.name}
                </Option>
              ))}
            </Select>
            <Select
              style={{ flex: 1 }}
              placeholder="选择角色"
              value={selectedRole}
              onChange={setSelectedRole}
            >
              {roles.map((role) => (
                <Option key={role.id} value={role.id}>
                  {role.name}
                </Option>
              ))}
            </Select>
            <Button
              icon={<ClearOutlined />}
              onClick={handleClearHistory}
              title="清除聊天记录"
            />
          </Space>
        </div>

        {/* 消息列表 */}
        <div style={{ flex: 1, overflow: 'auto', marginBottom: 16, backgroundColor: '#f5f5f5', borderRadius: 8, padding: 16 }}>
          {messages.length === 0 && (
            <div style={{ textAlign: 'center', paddingTop: 60 }}>
              <RobotOutlined style={{ fontSize: 48, color: '#1890ff' }} />
              <p style={{ color: '#666', marginTop: 16 }}>欢迎来到AI家族助手</p>
              <p style={{ color: '#999', fontSize: 14 }}>我可以帮您策划活动、制定规则、解答疑问</p>
              
              <div style={{ marginTop: 24 }}>
                <Space direction="vertical" style={{ width: '100%' }}>
                  {initialPrompts.map((prompt, index) => (
                    <Button
                      key={index}
                      type="text"
                      size="small"
                      style={{ width: '100%', textAlign: 'left' }}
                      onClick={() => handleSend(prompt)}
                    >
                      {prompt}
                    </Button>
                  ))}
                </Space>
              </div>
            </div>
          )}
          
          {messages.map(renderMessage)}
          <div ref={messagesEndRef} />
        </div>

        {/* 输入区域 */}
        <div>
          <Search
            placeholder="输入您的问题..."
            allowClear
            enterButton={<MessageOutlined />}
            size="large"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onSearch={handleSend}
            loading={loading}
          />
        </div>
      </div>
    </Modal>
  )
}

export default AIChatWindow